<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 使用栅格布局: 每行宽24格，gutter设置列距，span设置每列占多少格 -->
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="showAddCategoriesDialog"
            class="addCategoriesBtn"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 使用新的组件库TreeTable -->
      <tree-table
        :data="categoriesList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效 列 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="!scope.row.cat_deleted"
            style="color: lightgreen; font-size: 18px"
          ></i>
          <i
            class="el-icon-error"
            v-if="scope.row.cat_deleted"
            style="color: red; font-size: 18px"
          ></i>
        </template>
        <!-- 排序 列 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level === 2">三级</el-tag>
        </template>
        <!-- 操作 列 -->
        <template slot="operation" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="showEditCetagoriesDialog(scope.row)"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDeleteCategorise(scope.row)"
            icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCategoriesVisible"
      width="50%"
      @close="addCategoriesClosed"
    >
      <el-form
        :model="addCategoriesForm"
        :rules="categoriesFormRules"
        ref="addCategoriesFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoriesForm.cat_name"></el-input>
        </el-form-item>
        <!-- 默认为1级分类 -->
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCategoriesList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoriesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCetagories">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="editCategoriesVisible"
      width="50%"
      @close="$refs.editCategoriesFormRef.resetFields()"
    >
      <el-form
        :model="editCategoriesForm"
        :rules="categoriesFormRules"
        ref="editCategoriesFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCategoriesForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoriesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCetagories">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Categories',
  data() {
    return {
      // 分类列表
      categoriesList: [],
      // 控制对话框的显示与隐藏
      addCategoriesVisible: false,
      editCategoriesVisible: false,
      //   查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      //   为表格每列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          //  表示当前列使用自定义模板列，且模板名称为isOk
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          //  表示当前列使用自定义模板列，且模板名称为isOk
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          //  表示当前列使用自定义模板列，且模板名称为isOk
          type: 'template',
          template: 'operation',
        },
      ],
      //   添加分类
      addCategoriesForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      // 添加分类表单的验证规则
      categoriesFormRules: {
        cat_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: ['blur', 'change'],
          },
        ],
      },
      parentCategoriesList: [],
      selectedKeys: [],
      //   指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      editCategoriesForm: {},
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    async getCategoriesList() {
      //   get请求携带参数需要params
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('查询分类信息失败')
      }
      //   仔细查看文档和控制台，网络请求返回的是什么样的数据
      this.categoriesList = res.data.result
      this.total = res.data.total
    },
    // 控制每页的显示数据的大小
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCategoriesList()
    },
    // 更新显示哪一页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCategoriesList()
    },
    // 获取父级分类数据列表
    async getParentCategoriesList() {
      // 获取前两级的分类
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败')
      }
      this.parentCategoriesList = res.data
    },
    showAddCategoriesDialog() {
      this.getParentCategoriesList()

      this.addCategoriesVisible = true
    },
    // 当级联选择器的选择项发生变化时触发这个函数
    handleChange() {
      // 如果 selectedKeys 的长度大于0，则选中了父级。反之，没有选中父级
      const len = this.selectedKeys.length
      if (len > 0) {
        // 将 selectedKyes 的最后一项赋值给 cat_pid
        this.addCategoriesForm.cat_pid = this.selectedKeys[len - 1]
        // 为当前分类赋值
        this.addCategoriesForm.cat_level = len
        return
      } else {
        this.addCategoriesForm.cat_pid = 0
        this.addCategoriesForm.cat_level = 0
      }
    },
    // 添加新的分类
    addCetagories() {
      // 先对表单进行预校验
      this.$refs.addCategoriesFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 调用接口api，添加分类
        const { data: res } = await this.$http.post(
          'categories',
          this.addCategoriesForm
        )
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        // 关闭对话框
        this.addCategoriesVisible = false
        this.$message.success('添加分类成功')
        // 刷新表格
        this.getCategoriesList()
      })
    },
    addCategoriesClosed() {
      // 清空和重置元素
      this.$refs.addCategoriesFormRef.resetFields()
      this.selectedKeys = []
      this.addCategoriesForm.cat_level = 0
      this.addCategoriesForm.cat_pid = 0
    },
    // 编辑分类
    editCetagories() {
      // 先对表单进行预校验
      this.$refs.editCategoriesFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 调用接口api，添加分类
        const { data: res } = await this.$http.put(
          `categories/${this.editCategoriesForm.cat_id}`,
          {
            cat_name: this.editCategoriesForm.cat_name,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('更新分类失败')
        // 关闭对话框
        this.editCategoriesVisible = false
        this.$message.success('更新分类成功')
        // 刷新表格
        this.getCategoriesList()
      })
    },
    showEditCetagoriesDialog(cate) {
      this.editCategoriesVisible = true
      this.editCategoriesForm = cate
    },
    async handleDeleteCategorise(cate) {
      const confirmResult = await this.$confirm(
        `此操作将永久删除该分类 ${cate.cat_name}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: ref } = await this.$http.delete('categories/' + cate.cat_id)
      if (ref.meta.status !== 200) return
      this.$message.success(`分类 ${cate.cat_name} 删除成功!`)
      this.getCategoriesList()
    },
  },
}
</script>

<style lang="less" scoped>
.addCategoriesBtn {
  margin-bottom: 20px;
}

.el-cascader {
  width: 100%;
}
</style>